/*
 * Copyright (C) 2023  即时通讯网(52im.net) & Jack Jiang.
 * The MobileIMSDK v6.4 Project. 
 * All rights reserved.
 * 
 * > Github地址：https://github.com/JackJiang2011/MobileIMSDK
 * > 文档地址：  http://www.52im.net/forum-89-1.html
 * > 技术社区：  http://www.52im.net/
 * > 技术交流群：320837163 (http://www.52im.net/topic-qqgroup.html)
 * > 作者公众号：“【即时通讯技术圈】”，欢迎关注！
 * > 联系作者：  http://www.52im.net/thread-2792-1-1.html
 *  
 * "即时通讯网(52im.net) - 即时通讯开发者社区!" 推荐开源工程。
 * 
 * GlobalSendHelper.java at 2023-9-21 15:24:55, code by Jack Jiang.
 */
package server.utils;

import io.netty.channel.Channel;
import server.ServerCoreHandler;
import server.ServerLauncher;
import server.network.Gateway;
import server.network.MBObserver;
import server.processor.OnlineProcessor;
import server.protocal.Protocal;
import server.qos.QoS4ReciveDaemonC2S;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GlobalSendHelper
{
	private static Logger logger = LoggerFactory.getLogger(ServerCoreHandler.class);  

	public static void sendDataC2C( final Channel session, final Protocal pFromClient, final String remoteAddress
			, final ServerCoreHandler serverCoreHandler) throws Exception
	{
		// TODO just for DEBUG
		OnlineProcessor.getInstance().__printOnline();

			MBObserver resultObserver = new MBObserver(){
				@Override
				public void update(boolean sendOK, Object extraObj)
				{
					boolean needAck = false;
					
					if(sendOK)
					{
						needAck = true;
						serverCoreHandler.getServerEventListener().onTransferMessage4C2C(pFromClient);
					}
					else
					{
						logger.info("[IMCORE-{}<C2C>]>> 客户端{}的通用数据尝试实时发送没有成功，将交给应用层进行离线存储哦..."
								, Gateway.$(session), remoteAddress);

						boolean offlineProcessedOK = serverCoreHandler.getServerEventListener().onTransferMessage_RealTimeSendFaild(pFromClient);
						if(pFromClient.isQoS() && offlineProcessedOK)
						{
							needAck = true;
						}
						else
						{
							logger.warn("[IMCORE-{}<C2C>]>> 客户端{}的通用数据传输消息尝试实时发送没有成功，但上层应用层没有成功(或者完全没有)进行离线存储，此消息已被服务端丢弃！", Gateway.$(session), remoteAddress);
						}
					}
					
					if(needAck)
					{
						try
						{
							MBObserver retObserver = new MBObserver(){
								@Override
								public void update(boolean sucess, Object extraObj)
								{
									if(sucess)
									{
										logger.debug("[IMCORE-{}<C2C>]【QoS_伪应答_C2S】向{}发送{}的应答包成功,from={}."
												, Gateway.$(session), pFromClient.getFrom(), pFromClient.getFp(), pFromClient.getTo());
									}
								}
							};
							
							LocalSendHelper.replyRecievedBack(session, pFromClient, retObserver);
						}
						catch (Exception e)
						{
							logger.warn(e.getMessage(), e);
						}
					}
				}
			};
			
			LocalSendHelper.sendData(pFromClient, resultObserver);

	}
}
